import React, { useState, useEffect, lazy, Suspense } from 'react';
import {
  useNavigate,
  RouteObject,
  NonIndexRouteObject,
  Link,
  Routes,
  Route,
} from 'react-router-dom';
import { each, isArray } from 'lodash';
import { message, Result, Button } from 'antd';
import { isNil } from '@ant-design/pro-components';
import Skeleton from '@ant-design/pro-skeleton';

import { useAppSelector } from '@/app/common/hooks';
import ErrorBoundary from '@/app/common/components/ErrorBoundary';
import Layout from '@/app/pages/layout';
import Iframe from '../pages/Iframe';

interface RouterProps extends NonIndexRouteObject {
  cachePath: string;
}

function Root() {
  const routers = useAppSelector(s => s.user.routers);
  const [rout, setRout] = useState([]);
  const navigate = useNavigate();

  const LazyLoad = ({ name }: { name: string }) => {
    let Module: React.ComponentType<any> = lazy(() => import(`@/app/pages/${name}`));
    return (
      <ErrorBoundary>
        <Suspense fallback={<Skeleton type="list" />}>
          <Module />
        </Suspense>
      </ErrorBoundary>
    );
  };

  //判断登录权限
  useEffect(() => {
    if (location.pathname) {
      const token = localStorage.getItem('token');
      if ((token === null || !token) && location.pathname !== '/login') {
        message.success('登陆过期,跳转登陆页面...');
        navigate('/login');
      }
    }
  }, [location.pathname]);

  useEffect(() => {
    // 生成路由表
    const getRouters = (routers: RouteObject[] = [], parentPath = '') => {
      const temp: RouterProps[] = [];
      each(routers, (d: any) => {
        const path = !isNil(parentPath) ? `${parentPath}/${d.path.replace('/', '')}` : d.path;
        const component =
          d.component && d.component !== null && d.component !== 'Layout' ? (
            <LazyLoad name={`${d.component}`} />
          ) : (
            undefined
          );
        if (!d.hidden) {
          if (isArray(d.children) && d.children.length > 0) {
            temp.push(...getRouters(d.children, path));
          }
          temp.push({
            path,
            element: component,
            cachePath: d.meta && !d.meta.noChace ? path : '',
          });
        }
      });
      return temp;
    };
    const router = getRouters(routers)
      .filter(d => d.element)
      .map(d => ({ ...d, path: d.path.substring(1) }));
    setRout(router);
  }, [routers]);

  return (
    <Routes>
      <Route path="/*" element={<Layout />}>
        <Route index element={<LazyLoad name={'home'} />} />
        {rout.map(d => (
          <Route key={d.path} path={d.path} element={d.element} />
        ))}
        <Route path="iframe" element={<Iframe />} />
      </Route>
      <Route path="/login" element={<LazyLoad name={`login`} />} />
      <Route
        path="*"
        element={
          <Result
            status="404"
            title="404"
            subTitle="Sorry, the page you visited does not exist."
            extra={
              <Link to={'/'}>
                <Button type="primary">Back Home</Button>
              </Link>
            }
          />
        }
      />
    </Routes>
  );
}

export default Root;
